//
//  PYPublishChoiceView.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/11.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import ZLPhotoBrowser
import AVKit
import Photos

class PYPublishChoiceView: SYBaseView {

    public var choiceClosure: (([UIImage], URL?) -> Void)?
    fileprivate var bgView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = .white
        v.layer.shadowColor = UIColor(hex: 0xB3B3B3).cgColor
        v.layer.shadowOpacity = 0.5//阴影透明度
        v.layer.shadowOffset = CGSize(width: 0, height: -5)///阴影偏移量,四周
        v.layer.shadowRadius = 5//阴影半径  shadowPathWidth：阴影宽度
        return v
    }()
    
    let paisheLb: UILabel = {
        let v = UILabel()
        v.text = "照片或视频"
        v.textColor = UIColor(hex: 0x999999)
        v.font = 14.autoFontSize()
        v.textAlignment = .center
        return v
    }()
    
    let paishe: UIButton = {
        let v: UIButton  = UIButton()
        v.setTitle("拍摄", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        v.titleLabel?.font = 17.autoFontSize()
        v.backgroundColor = .white
        return v
    }()
    
    let xuanze: UIButton = {
        let v: UIButton  = UIButton()
        v.setTitle("从手机相册中选择", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        v.titleLabel?.font = 17.autoFontSize()
        return v
    }()
    
    let quxiao: UIButton = {
        let v: UIButton  = UIButton()
        v.setTitle("取消", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        v.titleLabel?.font = 17.autoFontSize()
        return v
    }()
    
    var sepView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = Constant.bgViewColor
        return v
    }()
    


    override func initViews() {
        
        self.isHidden = true
        paishe.addTarget(self, action: #selector(paisheAction), for: .touchUpInside)
        xuanze.addTarget(self, action: #selector(xuanzeAction), for: .touchUpInside)
        quxiao.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        addSubview(bgView)
        addSubview(paisheLb)
        addSubview(paishe)
        addSubview(xuanze)
        addSubview(quxiao)
        addSubview(sepView)
        addSubview(lineView)
        bgView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(5)
        }
        paisheLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(53)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(15)
        }
        paishe.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        xuanze.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(92)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(78)
        }
        quxiao.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(180)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(68)
        }
        sepView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(170)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(10)
        }
        lineView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(92)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
    }
    
    func selectPhoto() {
        
        // 微信样式
        let ps = ZLPhotoPreviewSheet()
        ps.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            if let `self` = self {
                
                if assets.first!.mediaType == .image {
                    (self.currentVC as! PYEditViewController).imageChoice.lastImages = images
                    self.choiceClosure?(images, nil)
                } else {
                    let option: PHVideoRequestOptions = PHVideoRequestOptions()
                    option.isNetworkAccessAllowed = true
                    if let a = assets.first {
                        
                        PHCachingImageManager().requestAVAsset(forVideo: a, options:option, resultHandler: { (asset, audioMix, info)in
                            var path: String = ""
                            if #available(iOS 13.0, *) {
                                if let urlAsset = (asset as? AVURLAsset) {
                                    path = urlAsset.url.absoluteString
                                }
                            } else {
                                if let urlAsset = (asset as? AVURLAsset) { // ios 12 之前此方法取不出慢视频地址
                                    path = urlAsset.url.absoluteString
                                } else if let i = info, let k: String = i["PHImageFileSandboxExtensionTokenKey"] as? String, let p = k.components(separatedBy: ";").last {
                                    path = p.replacingOccurrences(of: "/private/", with: "file:///private/")
                                }
                            }
                            if let avAsset = asset {
                                DispatchQueue.main.async(execute: {
                                    let vc = ZLEditVideoViewController(avAsset: avAsset)
                                    vc.editFinishBlock = { url in
                                        print(url)
                                        let image: UIImage = (self.getVideoFengMian(url: url.absoluteString))
                                        (self.currentVC as! PYEditViewController).imageChoice.lastImages = [image]
                                        self.choiceClosure?([image], url)
                                    }
                                    vc.modalPresentationStyle = .fullScreen
                                    self.currentVC.vg_present(vc, animated: false, completion: nil)
                                })
                            }
                        })
                    }
                }
            }
        }
        ps.showPhotoLibrary(sender: self.currentVC)
    }
    
    func camera() {

        let camera = ZLCustomCamera()
        camera.takeDoneBlock = { (image, url) in
            print(image, url)
            if let u = url {
                (self.currentVC as! PYEditViewController).imageChoice.lastImages = [self.getVideoFengMian(url: u.absoluteString)]
            }
            
            if let i = image {
                (self.currentVC as! PYEditViewController).imageChoice.lastImages = [i]
            }
            if let i = image {
                self.choiceClosure?([i], url)
            }
        }
        self.currentVC.showDetailViewController(camera, sender: self.currentVC)
    }
    
    func getVideoFengMian(url:String) -> UIImage {
        if url.isEmpty {
            //默认封面图
            return UIImage(named: "my_yijian")!
        }
        let aset = AVURLAsset(url: URL(fileURLWithPath: url), options: nil)
        let assetImg = AVAssetImageGenerator(asset: aset)
        assetImg.appliesPreferredTrackTransform = true
        assetImg.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
        do{
            let cgimgref = try assetImg.copyCGImage(at: CMTime(seconds: 10, preferredTimescale: 50), actualTime: nil)
            return UIImage(cgImage: cgimgref)
            
        }catch{
            return UIImage(named: "my_yijian")!
        }
        
    }
    
    @objc func paisheAction() {
        self.isHidden = true
        camera()
    }
    @objc func xuanzeAction() {
        self.isHidden = true
        selectPhoto()
    }
    @objc func cancelAction() {
        self.isHidden = true
    }
}
